<?php

namespace app\index\controller;

use app\index\model\Collect;
use app\index\model\Goods;
use app\index\model\Pictures;
use app\index\model\SkuKey;
use app\index\model\Spu;
use think\Controller;
use think\Db;

class GoodsCtl extends Controller
{
    /*
     * 获取商品属性的 key value
     */
    public function getSkuKeyVal()
    {
        $res['data'] = SkuKey::with('val')->select();
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 分页获取商品信息
     */
    public function getGoods()
    {
        $page = input('page', 1);
        $pageSize = input('pageSize', 12);
        $res = [];
        $minPrice = input('minPrice', 0);
        $maxPrice = input('maxPrice', 10000);
        // 是否按分类进行查询
        if (input('type') != '') {
            $goods = getGoodsByTypeWithPrice($page, $pageSize, input('type'), $minPrice, $maxPrice);
            $res["totalPage"] = ceil(Goods::where('classification_id', input('type'))->count('id') / $pageSize);
        } else {
            $goods = getGoodsWithPrice($page, $pageSize, $minPrice, $maxPrice);
            $res["totalPage"] = ceil(Goods::count('id') / $pageSize);
        }
        // 此处获取商品对应的规格、颜色等属性，同时获取预览图
        $goods = setPicAndSpuAndSku($goods);
        $res['data'] = $goods;
        $res['code'] = 20000;
        return json($res);
    }

    /*
 * 分页获取商品信息
 */
    public function getGoodsForAdmin()
    {
        $page = input('page', 1);
        $pageSize = input('pageSize', 12);
        $res = [];
        // 是否按分类进行查询
        if (input('type') != '') {
            $goods = Goods::where('classification_id', input('type'))->page($page, $pageSize)->select();
            $res["totalPage"] = ceil(Goods::where('classification_id', input('type'))->count('id') / $pageSize);
        } else {
            $goods = (new Goods)->page($page, $pageSize)->select();
            $res["totalPage"] = ceil(Goods::count('id') / $pageSize);
        }
        // 此处获取商品对应的规格、颜色等属性，同时获取预览图
        $goods = setPicAndSpuAndSku($goods);
        $res['data'] = $goods;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 搜索名称、简介匹配 key 的商品
     */
    public function searchGoods()
    {
        $page = input('page', 1);
        $pageSize = input('pageSize', 12);
        $key = "%" . input('key') . "%";    // 搜索的关键词
        $res = [];
        $goods = Goods::where('name', 'like', $key)
            ->whereOr('introduce', 'like', $key)
            ->page($page, $pageSize)
            ->select();
        $goods = setPicAndSpuAndSku($goods);
        // 传总页数给前端，方便分页
        $res["totalPage"] = ceil(
            Goods::where('name', 'like', $key)
                ->whereOr('introduce', 'like', $key)
                ->count('id') / $pageSize
        );
        $res['data'] = $goods;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 根据商品 Id 获取商品信息
     */
    public function getGoodsById()
    {
        $goods = Goods::get(input('id'), 'pictures');
        $goods = setSpuAndSku($goods);
        $res['data'] = $goods;
        $res['collected'] = Collect::where(['gid' => input('id'), 'uid' => input('uid')])->find() ? 1 : 0;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 添加商品基本信息（不包括价格、库存、规格等属性）
     */
    public function addGoods()
    {
        // 添加商品基本信息
        $goods = Goods::create([
            'name' => input('name'),
            'introduce' => input('introduce'),
            'source' => input('source'),
            'classification_id' => input('classification_id')
        ]);

        // 上传商品图片，构造 url 数组
        $pictures = uploadPic();    // 预览图

        // 插入商品图片
        if (count($pictures) > 0) {
            $goods->pictures()->saveAll($pictures);
        }

        $goods['pictures'] = $goods->pictures;
        $res['data'] = $goods;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 根据商品 id 添加图片
     */
    public function addGoodsPic()
    {
        $urls = uploadPic();
        if (count($urls) > 0) {
            $goods = Goods::get(input('id'));
            $goods->pictures()->saveAll($urls);
            return json(['msg' => '添加成功！', 'code' => 20000]);
        } else {
            return json(['msg' => '添加失败！', 'code' => 20000]);
        }
    }

    /*
     * 添加标准商品（包括具体的规格、颜色、价格、库存等属性）
     */
    public function addGoodsSpu()
    {
        $data = [
            'price' => input('price'),
            'stock' => input('stock'),
            'postage' => input('postage'),
            'gid' => input('gid')
        ];
        $spu_id = Db::table('spu')->insertGetId($data);
        $skuData = [];

        // 若添加时选择了某个属性，则记录下来
        foreach (input("sku") as $sku) {
            // 前端的 value 应为 "keyId,valId"
            list($keyId, $valId) = explode(",", $sku);
            $skuData[] = [
                'sid' => $spu_id,
                'key_id' => $keyId,
                'val_id' => $valId
            ];
        }

        Db::table('spu_sku')->insertAll($skuData);
        return json(['msg' => '添加成功！', 'code' => 20000]);
    }

    /*
     * 根据商品 id 删除商品
     */
    public function delGoods()
    {
        $id = input('id');
        // 删除商品规格、颜色等属性
        $spuId = Spu::where('gid', $id)->column('id');
        foreach ($spuId as $si) {
            $spu = Spu::get($si, 'sku');
            $spu->together("sku")->delete();
        }
        // 删除商品图片
        Pictures::where('gid', $id)->delete();
        // 删除商品
        Goods::destroy($id);
        return json(['msg' => '删除成功！', 'code' => 20000]);
    }

    /*
     * 根据图片 id 删除商品图片
     */
    public function delGoodsPic()
    {
        Pictures::destroy(input('id'));
        return json(['msg' => '删除成功！', 'code' => 20000]);
    }

    /*
     * 通过关联表 id 删除某个商品的某个规格
     */
    public function delGoodsSpec()
    {
        $spu = Spu::get(input('id'), 'sku');
        $spu->together('sku')->delete();
        return json(['msg' => '删除成功！', 'code' => 20000]);
    }

    /*
     * 更新商品基本信息
     */
    public function updGoodsInfo()
    {
        Goods::update([
            'id' => input('id'),
            'name' => input('name'),
            'introduce' => input('introduce'),
            'source' => input('source'),
            'classification_id' => input('classificationId')
        ]);
        return json(['msg' => '更新成功！', 'code' => 20000]);
    }

    /*
     * 更新标准商品的规格、颜色、价格等信息
     */
    public function updGoodsSpu()
    {
        Spu::update([
            'id' => input('id'),
            'price' => input('price'),
            'postage' => input('postage'),
            'stock' => input('stock')
        ]);
        return json(['msg' => '更新成功！', 'code' => 20000]);
    }

    public function indexFirFlood()
    {
        $res = Db::query("SELECT * FROM goods as t1 WHERE t1.id >= (RAND()*(SELECT MAX(id) FROM goods)) LIMIT 10;");
        foreach ($res as &$r) {
            $r['price'] = Spu::where('gid', $r['id'])->value('price');
            $r['picture'] = Pictures::where(['gid' => $r['id'], 'type' => 0])->value('url');
        }
        return json($res);
    }

    public function indexSecAndThird()
    {
        $res = Db::query("SELECT * FROM goods as t1 WHERE t1.id >= (RAND()*(SELECT MAX(id) FROM goods)) LIMIT 8");
        foreach ($res as &$r) {
            $r['price'] = Spu::where('gid', $r['id'])->value('price');
            $r['picture'] = Pictures::where(['gid' => $r['id'], 'type' => 0])->value('url');
        }
        return json($res);
    }

    public function newAndPromotion()
    {
        $res = Db::query("SELECT * FROM goods as t1 WHERE t1.id >= (RAND()*(SELECT MAX(id) FROM goods)) LIMIT 6");
        foreach ($res as &$r) {
            $r['price'] = Spu::where('gid', $r['id'])->value('price');
            $r['picture'] = Pictures::where(['gid' => $r['id'], 'type' => 0])->value('url');
        }
        return json($res);
    }

    public function activity()
    {
        $res = Db::query("SELECT * FROM goods as t1 WHERE t1.id >= (RAND()*(SELECT MAX(id) FROM goods)) LIMIT 6");
        foreach ($res as &$r) {
            $r['price'] = Spu::where('gid', $r['id'])->value('price');
            $r['picture'] = Pictures::where(['gid' => $r['id'], 'type' => 0])->value('url');
        }
        return json($res);
    }

    public function brand()
    {
        $res = Db::query("SELECT * FROM goods as t1 WHERE t1.id >= (RAND()*(SELECT MAX(id) FROM goods)) LIMIT 4");
        foreach ($res as &$r) {
            $r['price'] = Spu::where('gid', $r['id'])->value('price');
            $r['picture'] = Pictures::where(['gid' => $r['id'], 'type' => 0])->value('url');
        }
        return json($res);
    }

}